﻿using HCQ2_IBLL;
using HCQ2_Model;
using HCQ2_Model.APIBase;
using HCQ2_Model.VR.Model;
using HCQ2_Model.VR.Params;
using HCQ2_Model.VRDD.InputDto._210908;
using HCQ2_Model.VRDD.InputDto._211217;
using HCQ2_Model.VRDD.OutputDto._210908;
using HCQ2_Model.VRDD.OutputDto._211217;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace HCQ2_BLL
{
    public partial class T_VRDDSpecMainBLL: IT_VRDDSpecMainBLL
    {
        /// <summary>
        ///  获取规格列表
        /// </summary>
        /// <param name="isMoney">是否影响价格</param>
        /// <param name="isType">类型</param>
        /// <param name="specName">规格名称</param>
        /// <returns></returns>
        public List<SpecResultList> GetSpecResultList(int fileId,int isMoney, string isType, string specName)
        {
            var list = DBSession.IT_VRDDSpecMainDAL.GetSpecResultList(fileId,isMoney, isType, specName);
            list?.ForEach(s =>
            {
                string[] optionID = null,optionName = null;
                List<SpecOptionList> specOptionList = new List<SpecOptionList>();
                if (!string.IsNullOrEmpty(s.specOptionId))
                {
                    optionID = s.specOptionId.Split(',');
                    optionName = s.specOptionName.Split(',');
                }
                if(optionID!=null && optionID.Length > 0)
                {
                    for(int i=0;i< optionID.Length; i++)
                    {
                        int id = HCQ2_Common.Helper.ToInt(optionID[i]);
                        specOptionList.Add(new SpecOptionList
                        {
                            optionID = id,
                            optionName = optionName[i]
                        });
                    }
                    s.specOptionList = specOptionList;
                }
            });
            return list;
        }
        /// <summary>
        ///  删除已不在的子规格数据
        /// </summary>
        /// <param name="optionId"></param>
        /// <param name="specId"></param>
        /// <returns></returns>
        public int DeleteSpecChild(List<string> optionId, int specId)
        {
            return DBSession.IT_VRDDSpecMainDAL.DeleteSpecChild(optionId, specId);
        }
        /// <summary>
        ///  获取待删除子规格图片附件地址
        /// </summary>
        /// <param name="optionId"></param>
        /// <param name="specId"></param>
        /// <returns></returns>
        public List<string> GetDeleteSpecChildPic(List<string> optionId, int specId)
        {
            return DBSession.IT_VRDDSpecMainDAL.GetDeleteSpecChildPic(optionId, specId);
        }
        /// <summary>
        ///  重置库存、价格数据信息
        /// </summary>
        /// <param name="fileId"></param>
        /// <returns></returns>
        public bool ResetSpecChildOption(int fileId)
        {
            //1.1、删除组合数据【库存】
            DBSession.IT_VRDDSpecGroupDAL.Delete(s => s.fileId == fileId);
            //1.1、删除组合数据【价格】
            DBSession.IT_VRDDSpecGroupPriceDAL.Delete(s => s.fileId == fileId);
            //1.2、删除库存数据
            DBSession.IT_VRDDSpecRepertoryDAL.Delete(s => s.fileId == fileId);
            //1.3、删除价格数据
            DBSession.IT_VRDDSpecPriceDAL.Delete(s => s.fileId == fileId);
            List<VRSpecChildOption> list = DBSession.IT_VRDDSpecMainDAL.GetSpecChildOption(fileId);
            if (list == null || list.Count <= 0)
            {
                //无规格情况下
                //1、生成【库存】
                string code1 = HCQ2_Common.Helper.GetGuid;
                var group = new T_VRDDSpecGroup
                {
                    keyCode = HCQ2_Common.Helper.GetGuid,
                    groupCode = code1,
                    optionID = 0,
                    specID = 0,
                    fileId = fileId,
                    specMoney = true
                };
                //添加组合
                DBSession.IT_VRDDSpecGroupDAL.Add(group);
                //添加库存表
                DBSession.IT_VRDDSpecRepertoryDAL.Add(new T_VRDDSpecRepertory { keyCode = HCQ2_Common.Helper.GetGuid, fileId = fileId, quantity = 0, groupCode = code1 });
                //2、生成【价格】
                //没有影响价格的规格时，添加空规格
                string code2 = HCQ2_Common.Helper.GetGuid;
                //添加组合
                DBSession.IT_VRDDSpecGroupPriceDAL.Add(new T_VRDDSpecGroupPrice
                {
                    keyCode = HCQ2_Common.Helper.GetGuid,
                    groupCode = code2,
                    optionID = 0,
                    specID = 0,
                    fileId = fileId
                });
                //添加价格表
                DBSession.IT_VRDDSpecPriceDAL.Add(new T_VRDDSpecPrice { keyCode = HCQ2_Common.Helper.GetGuid, fileId = fileId, specMoney = 0, groupCode = code2 });
            }
            else
            {
                //有规格情况下 
                var obj = DBSession.IT_VRDDSpecMainDAL.Select(s => s.fileId == fileId);
                //库存
                List<List<VRSpecChildOption>> optionList = new List<List<VRSpecChildOption>>();
                //价格
                List<List<VRSpecChildOption>> priceList = new List<List<VRSpecChildOption>>();
                //2.0、生成规格组合表【库存】、【价格】
                obj.ForEach(s =>
                {
                    var t = list.Where(o => o.specID == s.specID)?.ToList();
                    optionList.Add(t);
                    if (s.specMoney)
                        priceList.Add(t);
                });
                //生成【库存】
                if (optionList!=null && optionList.Count > 0)
                {
                    int index = 1;
                    //循环第一层
                    for (int i = 0; i < optionList[0].Count; i++)
                    {
                        if (index < optionList.Count)
                        {
                            #region 多层级递归处理
                            List<VRSpecChildOption> _firstList = ResetSepcData(optionList, optionList[0][i], index);
                            _firstList?.ForEach(s =>
                            {
                                string[] options = s.options.Trim(',').Split(',');
                                int num = 0;
                                foreach(var id in options)
                                {
                                    int option_id = HCQ2_Common.Helper.ToInt(id);
                                    var spec = list.Where(n => n.optionID == option_id)?.FirstOrDefault();
                                    var group = new T_VRDDSpecGroup
                                    {
                                        keyCode = HCQ2_Common.Helper.GetGuid,
                                        groupCode = s.code,
                                        optionID = option_id,
                                        specID = spec.specID,
                                        fileId = fileId,
                                        specMoney = spec.specMoney
                                    };
                                    if (spec.specMoney)
                                        num = 1;
                                    //添加组合
                                    DBSession.IT_VRDDSpecGroupDAL.Add(group);
                                }
                                //添加库存表
                                DBSession.IT_VRDDSpecRepertoryDAL.Add(new T_VRDDSpecRepertory { keyCode = HCQ2_Common.Helper.GetGuid, fileId =fileId,quantity=0, groupCode=s.code});
                            });
                            #endregion
                        }
                        else
                        {
                            #region 只有一层
                            string code = HCQ2_Common.Helper.GetGuid;
                            var group = new T_VRDDSpecGroup
                            {
                                keyCode = HCQ2_Common.Helper.GetGuid,
                                groupCode = code,
                                optionID = optionList[0][i].optionID,
                                specID = optionList[0][i].specID,
                                fileId = fileId,
                                specMoney = optionList[0][i].specMoney
                            };
                            //添加组合
                            DBSession.IT_VRDDSpecGroupDAL.Add(group);
                            //添加库存表
                            DBSession.IT_VRDDSpecRepertoryDAL.Add(new T_VRDDSpecRepertory { keyCode = HCQ2_Common.Helper.GetGuid, fileId = fileId, quantity = 0, groupCode = code });
                            #endregion
                        }
                    }
                }
                //生成【价格】
                if (priceList != null && priceList.Count > 0)
                {
                    int index = 1;
                    //循环第一层
                    for (int i = 0; i < priceList[0].Count; i++)
                    {
                        if (index < priceList.Count)
                        {
                            #region 多层级递归处理
                            List<VRSpecChildOption> _firstList = ResetSepcData(priceList, priceList[0][i], index);
                            _firstList?.ForEach(s =>
                            {
                                string[] options = s.options.Trim(',').Split(',');
                                int num = 0;
                                foreach (var id in options)
                                {
                                    int option_id = HCQ2_Common.Helper.ToInt(id);
                                    var spec = list.Where(n => n.optionID == option_id)?.FirstOrDefault();
                                    var group = new T_VRDDSpecGroupPrice
                                    {
                                        keyCode = HCQ2_Common.Helper.GetGuid,
                                        groupCode = s.code,
                                        optionID = option_id,
                                        specID = spec.specID,
                                        fileId = fileId
                                    };
                                    if (spec.specMoney)
                                        num = 1;
                                    //添加组合
                                    DBSession.IT_VRDDSpecGroupPriceDAL.Add(group);
                                }
                                //添加价格表
                                if (num > 0)
                                    DBSession.IT_VRDDSpecPriceDAL.Add(new T_VRDDSpecPrice { keyCode = HCQ2_Common.Helper.GetGuid, fileId = fileId, specMoney = 0, groupCode = s.code });
                            });
                            #endregion
                        }
                        else
                        {
                            #region 只有一层
                            string code = HCQ2_Common.Helper.GetGuid;
                            var group = new T_VRDDSpecGroupPrice
                            {
                                keyCode = HCQ2_Common.Helper.GetGuid,
                                groupCode = code,
                                optionID = priceList[0][i].optionID,
                                specID = priceList[0][i].specID,
                                fileId = fileId
                            };
                            //添加组合
                            DBSession.IT_VRDDSpecGroupPriceDAL.Add(group);
                            //添加价格表
                            if (priceList[0][i].specMoney)
                                DBSession.IT_VRDDSpecPriceDAL.Add(new T_VRDDSpecPrice { keyCode = HCQ2_Common.Helper.GetGuid, fileId = fileId, specMoney = 0, groupCode = code });
                            #endregion
                        }
                    }
                }
                else
                {
                    //没有影响价格的规格时，添加空规格
                    string code = HCQ2_Common.Helper.GetGuid;
                    //添加组合
                    DBSession.IT_VRDDSpecGroupPriceDAL.Add(new T_VRDDSpecGroupPrice
                    {
                        keyCode = HCQ2_Common.Helper.GetGuid,
                        groupCode = code,
                        optionID = 0,
                        specID = 0,
                        fileId = fileId
                    });
                    //添加价格表
                    DBSession.IT_VRDDSpecPriceDAL.Add(new T_VRDDSpecPrice { keyCode = HCQ2_Common.Helper.GetGuid, fileId = fileId, specMoney = 0, groupCode = code });
                }
            }
            return true;
        }
        /// <summary>
        ///  
        /// </summary>
        /// <param name="optionList">原始数据</param>
        /// <param name="index">当前索引</param>
        /// <returns></returns>
        private List<VRSpecChildOption> ResetSepcData(List<List<VRSpecChildOption>> optionList, VRSpecChildOption item, int index)
        {
            List<VRSpecChildOption> option = new List<VRSpecChildOption>();
            int childIndex = index;
            if (childIndex >= optionList.Count)
                return null;
            ++childIndex;
            for (int i = 0; i < optionList[index].Count; i++)
            { 
                if (childIndex < optionList.Count)
                {
                    List<VRSpecChildOption> child = ResetSepcData(optionList, optionList[index][i], childIndex);
                    child.ForEach(s => {
                        s.options += $",{item.optionID}";
                        option.Add(s);
                    });
                }
                else
                {
                    VRSpecChildOption temp = new VRSpecChildOption
                    {
                        specID = optionList[index][i].specID,
                        specMoney = optionList[index][i].specMoney,
                        fileId = optionList[index][i].fileId,
                        optionID = optionList[index][i].optionID,
                        code = HCQ2_Common.Helper.GetGuid,
                        options = $"{optionList[index][i].optionID},{item.optionID}"
                    };
                    option.Add(temp);
                }      
            }
            return option;
        }

        /// <summary>
        ///  获取商品库存列表
        /// </summary>
        /// <param name="fileId"></param>
        /// <returns></returns>
        public List<SpecRepertoryModel> GetSpecRepertoryList(int fileId)
        {
            return DBSession.IT_VRDDSpecMainDAL.GetSpecRepertoryList(fileId);
        }
        /// <summary>
        ///  获取商品价格列表
        /// </summary>
        /// <param name="fileId"></param>
        /// <returns></returns>
        public List<SpecPriceModel> GetSpecPriceList(int fileId)
        {
            return DBSession.IT_VRDDSpecMainDAL.GetSpecPriceList(fileId);
        }

        //接口
        /// <summary>
        ///  获取商品规格列表
        /// </summary>
        /// <param name="fileId"></param>
        /// <returns></returns>
        public List<CommSpecOutput> GetCommSpecOutput(int fileId)
        {
            List<CommSpecOutput> list = new List<CommSpecOutput>();
            List<T_VRDDSpecMain> specList = DBSession.IT_VRDDSpecMainDAL.Select(s => s.fileId == fileId)?.ToList();
            specList?.ForEach(s =>
            {
                CommSpecOutput c = new CommSpecOutput
                {
                    specID = s.specID,
                    specName = s.specName,
                    specMoney = s.specMoney
                };
                var optionList = DBSession.IT_VRDDSpecChildDAL.Select(o => o.specID == s.specID)?.ToList();
                List<SpecOptionOutputModel> specOptionList = new List<SpecOptionOutputModel>();
                optionList?.ForEach(n =>
                {
                    var t = new SpecOptionOutputModel
                    {
                        optionID = n.optionID,
                        optionName = n.optionName
                    };
                    if (!string.IsNullOrEmpty(n.optionImage))
                        t.optionImage = n.optionImage.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
                    specOptionList.Add(t);
                });
                c.specOptionList = specOptionList;
                list.Add(c);
            });
            return list;
        }
        /// <summary>
        ///  获取规格组合价格
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public ResultServiceData GetCommPrice(CommPriceInput param)
        {
            ResultServiceData result = new ResultServiceData { isOk = true };
            //1、获取对应组合集合
            var list = DBSession.IT_VRDDSpecMainDAL.GetCommPriceList(param);
            if (list == null || list.Count <= 0)
            {
                result.data = 0;
                result.errMsg = "无此组合数据请检查！";
                return result;
            }
            if (list.Count > param.specOptionList.Count)
            {
                result.isOk = false;
                result.errMsg = "规格价格组合不完整！";
                result.data = 0;
                return result;
            }
            HashSet<string> set = new HashSet<string>(list.Select(s => s.groupCode));
            if (set.Count > 1)
            {
                result.isOk = false;
                result.errMsg = "规格价格组合不完整！";
                result.data = 0;
                return result;
            }
            result.data= DBSession.IT_VRDDSpecMainDAL.GetCommPrice(param.fileID, list[0].groupCode);
            return result;
        }
        /// <summary>
        ///  获取规格组合库存
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public ResultServiceData GetCommStock(CommPriceInput param)
        {
            ResultServiceData result = new ResultServiceData { isOk = true };
            //1、获取对应组合集合
            var list = DBSession.IT_VRDDSpecMainDAL.GetCommStockList(param);
            if (list == null || list.Count <= 0)
            {
                result.data = 0;
                result.errMsg = "无此组合数据请检查！";
                return result;
            }
            if (list.Count > param.specOptionList.Count)
            {
                result.isOk = false;
                result.errMsg = "规格库存组合不完整！";
                result.data = 0;
                return result;
            }
            HashSet<string> set = new HashSet<string>(list.Select(s => s.groupCode));
            if (set.Count > 1)
            {
                result.isOk = false;
                result.errMsg = "规格库存组合不完整！";
                result.data = 0;
                return result;
            }
            result.data = DBSession.IT_VRDDSpecMainDAL.GetCommStock(param.fileID, list[0].groupCode);
            return result;
        }
        /// <summary>
        ///  app获取规格列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public List<OutputDDSpecList> GetDDSpecList(InputDDSpecParam param)
        {
            var list = DBSession.IT_VRDDSpecMainDAL.GetDDSpecList(param);
            list?.ForEach(s =>
            {
                List<DDSpecChildList> specChild = new List<DDSpecChildList>();
                var specList = DBSession.IT_VRDDSpecChildDAL.Select(o => o.specID == s.specID);
                specList?.ForEach(n => {
                    var option = new DDSpecChildList { optionID=n.optionID,optionName=n.optionName};
                    if (!string.IsNullOrEmpty(n.optionImage))
                        option.optionImage = n.optionImage.Replace("~", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/")));
                    specChild.Add(option);
                });
                s.specChild = specChild;
            });
            return list;
        }
    }
}